package com.smh.yunpicturebackend.interceptors;

import com.auth0.jwt.interfaces.Claim;
import com.smh.yunpicturebackend.exception.ErrorCode;
import com.smh.yunpicturebackend.pojo.constant.AuthConstant;
import com.smh.yunpicturebackend.pojo.domain.User;
import com.smh.yunpicturebackend.utils.JWTUtils;
import com.smh.yunpicturebackend.utils.ThrowUtils;
import com.smh.yunpicturebackend.utils.UserThreadLocal;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Map;

/**
 * @author shiminghui
 * @date 2025/6/14 21:13
 * @description: TODO
 */
public class AuthInterceptor implements HandlerInterceptor {
    public static User parseUserForRequest(HttpServletRequest request) {
        // 改为从cookie中获取
        Cookie[] cookies = request.getCookies();
        ThrowUtils.throwIf(cookies == null, ErrorCode.NOT_LOGIN_ERROR);

        Cookie cookie = Arrays.stream(cookies).filter(item -> item.getName().equals(AuthConstant.AUTHORIZATION_HEADER)).findFirst().orElseGet(() -> null);
        ThrowUtils.throwIf(cookie == null, ErrorCode.NOT_LOGIN_ERROR);

        String token = cookie.getValue();
        ThrowUtils.throwIf(token == null || token.isEmpty(), ErrorCode.NOT_LOGIN_ERROR);

        // 验证token
        ThrowUtils.throwIf(!JWTUtils.verify(token), ErrorCode.NOT_LOGIN_ERROR);

        // 解析token
        Map<String, Claim> claims = JWTUtils.decode(token);

        // 将token中的用户信息保存到线程 中
        User user = new User();
        user.setId(claims.get("id").asLong());
        user.setUserAccount(claims.get("userAccount").asString());
        user.setUserName(claims.get("userName").asString());
        user.setUserRole(claims.get("userRole").asString());
        UserThreadLocal.set(user);
        return user;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 放行OPTIONS 请求
        if (request.getMethod().equals("OPTIONS")) {
            return true;
        }

        // 获取请求头中的token
//        String token = request.getHeader(AuthConstant.AUTHORIZATION_HEADER);

        parseUserForRequest(request);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
